package com.hydong.tvdemo

import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.SimpleTask
import com.blankj.utilcode.util.ToastUtils
import com.hydong.tvdemo.bean.ChannelBean
import com.hydong.tvdemo.bean.FilmBean
import com.hydong.tvdemo.bean.VideoBean
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements


class JsoupActivity : BaseActivity() {

    var filmList: MutableList<FilmBean> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_jsoup)


        val webUrl = "http://www.kcdsg.com/sohu/?wd=梦华录" // 梦华录 生活大爆炸
//        getFilmList(webUrl)


        getVideoPlayUrl("http://www.kcdsg.com/Helps/81788-2-22.html")

        // 视频调试页面
        // https://player.alicdn.com/detection.html

        // 视频资源
        // https://c2.monidai.com/20220611/Smy9Wqgy/index.m3u8?_t=1655394695708
        // https://c2.monidai.com/20220611/Smy9Wqgy/index.m3u8
    }

    private fun getVideoPlayUrl(mUrl: String) {
        ThreadUtils.executeByIo(object : SimpleTask<Void?>() {
            override fun doInBackground(): Void? {
                val doc: Document = Jsoup.connect(mUrl).get() as Document

                val element: Element? = doc.select("#cms_play").first()
                Log.e("DHY__", "爬虫 -->  element = ${element.toString()}")


//                val element = doc.select("iframes[src$=.m3u8]").first() // iframes with src ending .m3u8
//                Log.e("DHY__", "爬虫 -->  element = ${element.toString()}")

//                val iframes: Elements? = doc.select("iframe")
//                Log.e("DHY__", "爬虫 -->  iframes.size = ${iframes?.size}")
//                iframes?.also { list ->
//                    list.forEach {
//                        var src = it.attr("src")
//                        Log.e("DHY__", "爬虫 -->  src = $src")
//                    }
//                }

                return null
            }

            override fun onSuccess(result: Void?) {
            }
        })
    }

    private fun getVideoDetails() {
        if (filmList?.isEmpty()) {
            ToastUtils.showShort("搜索结果为空")
            return
        }

        var filmBean: FilmBean? = null
        filmList.forEach {
            if (!it.hasGet) {
                filmBean = it
                return@forEach
            }
        }

        filmBean?.also {
            val mUrl = it.url
            Log.e("DHY__", "爬虫 2 -->  mUrl = $mUrl")

            ThreadUtils.executeByIo(object : SimpleTask<Void?>() {
                override fun doInBackground(): Void? {
                    var channelList: MutableList<ChannelBean> = ArrayList()

                    val doc: Document = Jsoup.connect(mUrl).get() as Document
                    val playlist: Element? = doc.getElementsByClass("playlist").first()
                    val uls: Elements? = playlist?.getElementsByTag("ul")
//                    val uls = playlist?.select("ul.clearfix fade")
                    Log.e("DHY__", "uls.size = ${uls?.size}")
                    uls?.forEachIndexed { index, ul ->
                        val lis = ul?.getElementsByTag("li")
                        Log.e("DHY__", "lis.size = ${lis?.size}")

                        var channelBean = ChannelBean("Channel-$index", ArrayList())
                        var videoList: MutableList<VideoBean> = ArrayList()
                        lis?.forEach { li ->
                            val link = li.getElementsByTag("a").first()
                            val linkHref = link?.attr("href") ?: ""
                            val linkText = link?.text() ?: ""
                            Log.e("DHY__", "-->  $linkText $linkHref")
                            videoList.add(VideoBean(linkText, linkHref))
                        }
                        channelBean.videoList = videoList
                        channelList.add(channelBean)
                    }

                    it.hasGet = true
                    it.channelList = channelList
                    return null
                }

                override fun onSuccess(result: Void?) {
                    getVideoDetails()
                }
            })
        }

        if (filmBean == null) {
            Log.e("DHY__", "爬虫完成 Done !!!}")
            filmList.forEach {
                Log.e("DHY__", "============================================== \n${it.toString()}}")
            }
        }
    }

    private fun getFilmList(webUrl: String) {
        Log.e("DHY__", "爬虫 1 -->  mUrl = $webUrl")
        ThreadUtils.executeByIo(object : SimpleTask<MutableList<FilmBean>?>() {
            override fun doInBackground(): MutableList<FilmBean>? {
                var film: MutableList<FilmBean> = ArrayList()

                // 解析html
                val doc: Document = Jsoup.connect(webUrl).get() as Document
                val content: Element = doc.getElementById("content") as Element
                val itemList = content.getElementsByClass("details-info-min")
                for (item in itemList) {
                    // 左侧海报
                    val left = item.select("div.news-box-txt-l")
                    val link = left[0].getElementsByTag("a").first()
                    val linkHref = link?.attr("href") ?: ""
                    val linkText = link?.text() ?: ""
                    var img = link?.attr("data-original") ?: ""
                    // Log.e("DHY__", "爬虫结果 1 -->  $linkHref $linkText $img")

                    // 右侧详情
                    val right = item.select("div.details-info0")

                    var bean = FilmBean(linkText, linkHref, img)
                    Log.e("DHY__", "爬虫结果 1 -->  bean = ${bean.toString()}")
                    film.add(bean)
                }
                return film
            }

            override fun onSuccess(result: MutableList<FilmBean>?) {
                Log.e("DHY__", "爬虫结果 1 onSuccess -->  size = ${result?.size}")
                filmList.clear()
                filmList.addAll(result!!)

                getVideoDetails()
            }
        })
    }
}